<?php


namespace app\admin\model;

use think\Model;

/**
 * 附件模型
 * @package app\admin\model
 */
class Attachment extends Model
{
    // 设置当前模型对应的完整数据表名称
    protected $name = 'system_upload';

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;

    /**
     * 根据附件id获取路径
     * @param string|array $id 附件id
     * @param int $type 类型：0-补全目录，1-直接返回数据库记录的地址
     * @return array|bool|mixed|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\db\Express
     * @author dragonlhp <1458485514@qq.com>
     */
    public static function getFilePath($id = '', $type = 0)
    {
        if (is_array($id)) {
            $data_list = self::where('id', 'in', $id)->select();
            $paths = [];
            foreach ($data_list as $key => $value) {
                if ($value['driver'] == 'local') {
                    $paths[$value['id']] = ($type == 0 ? public_path() : '') . $value['path'];
                } else {
                    $paths[$value['id']] = $value['path'];
                }
            }
            return $paths;
        } else {
            $data = self::where('id', $id)->find();
            if ($data) {
                if ($data['driver'] == 'local') {
                    return ($type == 0 ? public_path() : '') . $data['path'];
                } else {
                    return $data['path'];
                }
            } else {
                return false;
            }
        }
    }

    /**
     * 根据附件id获取名称
     * @param string $id 附件id
     * @return string     名称
     */
    public static function getFileName($id = '')
    {
        return self::where('id', $id)->value('name');
    }
    /**
     * 计算附件大小单位
     * @param mixed $value
     * @return string
     */
    public function getSizeAttr($value)
    {
        return format_file_size($value);
    }
}
